#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex;// 创建锁变量

int ticket = 100;

void* get_tickets(void* arg)
{
  long id = (long)arg;
  while (1){
    usleep(1000);
    // 加锁
    pthread_mutex_lock(&mutex);
    if (ticket > 0){
      // 有票
      --ticket;
      printf("thread %ld get a ticket, the number of remaining is %d\n", id , ticket);
      // 解锁
      pthread_mutex_unlock(&mutex);
    }else{
      // 无票，退出
      // 解锁
      pthread_mutex_unlock(&mutex);
      break;
    }
  }
}

int main()
{
  pthread_t t[5];
  // 初始化锁
  pthread_mutex_init(&mutex, NULL);
  // 创建5个线程
  long i = 0;
  for (; i < 5; ++i)
  {
    pthread_create(t+i, NULL, get_tickets, (void*)(i+1));
  }
  
  // 释放5个线程
  for (i = 0; i < 5; ++i)
  {
    pthread_join(t[i], NULL);
  }
  // 销毁锁
  pthread_mutex_destroy(&mutex);
  return 0;
}
